<script setup>
import {ref,onMounted} from 'vue';
import { listApi as getAllClazzApi} from '@/api/clazz';
import { queryPageApi,addStudentApi,queryByIdApi,updateStudentApi,deleteStuApi,stuDisciplineApi} from '@/api/stu';
import { ElMessage ,ElMessageBox} from 'element-plus'
import { deleteByIdApi } from '../../api/emp';

//条件查询表单
const queryStuFrom=ref({name: '',degree:'',clazzId:''})
//学历数据
const degreeList=ref([{name : '初中',value : 1},{name : '高中',value : 2},{name : '大专',value : 3},{name : '本科',value : 4},{name : '硕士',value : 5},{name : '博士',value : 6}])
//性别列表数据
const genders = ref([{ name: '男', value: 1 }, { name: '女', value: 2 }])

//班级数据
const clazzList=ref([]);

// 控制弹窗
const dialogVisible = ref(false);
const dialogTitle = ref('新增学员');

//表格展示数据
const stuList=ref([]);

//表单数据
const stuFrom=ref({
    name: '',
    no: '',
    gender: '',
    phone: '',
    idCard: '',
    isCollege: '',
    address: '',
    degree: '',
    graduationDate: '',
    clazzId: ''
})

//表单校验规则引用
const stuFormRef=ref();

   // 分页
 const currentPage = ref(1);
const pageSize = ref(10);
const background = ref(true);
const total=ref(0);
const dialogviolationFormVisible=ref(false);
// 违纪
const violationFrom=ref({
  id : '',
  score : ''
});

// 每页展示记录数变化
const handleSizeChange = (val) => {
  search();
}

// 页码变化时触发
const handleCurrentChange = (val) => {
  search();
}

//查询数据
const search=async ()=>{
  const result=await queryPageApi(queryStuFrom.value.name,queryStuFrom.value.degree,queryStuFrom.value.clazzId,currentPage.value,pageSize.value);
  if (result.code) {
    stuList.value=result.data.rows;
    total.value=result.data.total;
  }
}

//清空搜索栏
const clear=()=>{
  queryStuFrom.value={name: '',degree:'',clazzId:''};
  search();
}
//查询全部班级信息
const getAllClazz= async()=>{
  const result=await getAllClazzApi();
  if (result.code) {
    clazzList.value=result.data;
  }
}

//钩子函数
onMounted(()=>{
  getAllClazz();
  search();
})

//新增对话框
const addStu=()=>{
  dialogVisible.value=true;
  dialogTitle.value='新增学员';
  stuFrom.value={
      name: '',
      no: '',
      gender: '',
      phone: '',
      idCard: '',
      isCollege: '',
      address: '',
      degree: '',
      graduationDate: '',
      clazzId: ''
  };
  if (stuFormRef.value) {
    stuFormRef.value.resetFields();
  }
}

//保存
const save=async ()=>{
  if(!stuFormRef.value) return;
  //表单校验
  await stuFormRef.value.validate( async(valid) => {
    if (valid) {
      let result;
      if (stuFrom.value.id) {
         result=await updateStudentApi(stuFrom.value);    
      }else{
       result=await addStudentApi(stuFrom.value);
      }
      if (result.code) {
        ElMessage.success(result.msg);
        dialogVisible.value=false;
        search();
      }else{
        ElMessage.error(result.msg);
      }
    }else{
      ElMessage.error('表单校验失败');
    }
  });
  
}

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度应在2到10个字符之间', trigger: 'blur' }
  ],
  no: [
    { required: true, message: '请输入学号', trigger: 'change' },
    { min: 10, max: 10, message: '长度必须为10', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur'  },
    /**
     * 正则表达式: / ..... / ;  ^ : 以...开始 ;  $ : 以 ... 结束
     * [3-9] : 范围 3-9 之间
     * \d : 数字, [0-9]
     * {9} : 量词
     */
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { min: 18, max: 18, message: '长度必须为18', trigger: 'blur' }
  ],
  isCollege: [
    { required: true, message: '是否院校学生', trigger: 'change' }
  ]
});

//修改的查询回显
const Edit= async(id)=>{
  const result=await queryByIdApi(id);
  if (result.code) {
    stuFrom.value=result.data;
    dialogVisible.value=true;
    dialogTitle.value='修改学员'; 
  }else{
    ElMessage.error(result.msg);
  }
}

//删除
const deleteById=async (id)=>{
  ElMessageBox.confirm('确认删除数据吗?','提示',{confirmButtonText: '确认',cancelButtonText: '取消',type: 'error'}
  ).then(async() => {
    const result=await deleteStuApi(id);
  if(result.code){
    ElMessage.success(result.msg);
    search();
  }else{
    ElMessage.error(result.msg);
  }
    }).catch(() => {
      ElMessage.info("取消删除")
    }) 
}

//记录勾选的学员的id
let stuIds=ref([]);

//复选框勾选发生变化时触发 - selection: 当前选中的记录 (数组)
const handleSelectionChange = (selectionData) => {
  stuIds.value=selectionData.map(data=>data.id);
  
}

//批量删除
const deleteByIds=async ()=>{
  ElMessageBox.confirm('确认删除数据吗?','提示',{confirmButtonText: '确认',cancelButtonText: '取消',type: 'error'}
  ).then(async() => {
      if (stuIds.value && stuIds.value.length>0 ) {
            const result=await deleteStuApi(stuIds.value);
          if(result.code){
            ElMessage.success(result.msg);
            search();
          }else{
            ElMessage.error(result.msg);
          }
       }else{
        ElMessage.info('您没有选择任何要删除的数据');
       }
 
    }).catch(() => {
      ElMessage.info("取消删除")
    }) 
}

// 打开违纪对话框
const openViolationDialog = (id) => {
  dialogviolationFormVisible.value = true;
  violationFrom.value = {
    id: id,
    score: ''
  };
};

// 保存违纪信息
const saveViolation = async () => {
  if (!violationFrom.value.score) {
    ElMessage.error('请输入违纪分数');
    return;
  }
  const result = await stuDisciplineApi(violationFrom.value.id, violationFrom.value.score);
  if (result.code) {
    ElMessage.success(result.msg);
    dialogviolationFormVisible.value = false;
    search();  
  }else{
    ElMessage.error(result.msg);
  }
 
}
</script>

<template>
  <h1>学员管理</h1>
  <!-- 搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="queryStuFrom" class="demo-form-inline">
    <el-form-item label="姓名">
      <el-input v-model="queryStuFrom.name" placeholder="请输入学员姓名" clearable />
    </el-form-item>
    <el-form-item label="最高学历">
      <el-select
        v-model="queryStuFrom.degree"
        placeholder="请选择"
        clearable>
        <el-option v-for="degrees in degreeList" :key="degrees.name" :label="degrees.name" :value="degrees.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="所属班级">
      <el-select
        v-model="queryStuFrom.clazzId"
        placeholder="请选择"
        clearable>
        <el-option v-for="clazzs in clazzList" :key="clazzs.id" :label="clazzs.name"  :value="clazzs.id" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="info" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>
 <!-- 按钮 -->
 <div class="container">
    <el-button type="primary" @click="addStu">+ 新增学院</el-button>
    <el-button type="danger" @click="deleteByIds">- 批量删除</el-button>
   </div><br>
  <!-- 表格 -->
  <div class="container">
    <el-table :data="stuList" border style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"  align="center"/>
    <el-table-column prop="name" label="姓名" width="100" align="center"/>
    <el-table-column prop="no" label="学号" width="120" align="center"/>
    <el-table-column prop="clazzName" label="班级" width="120" align="center"/>
    <el-table-column  label="性别" width="55" align="center">
      <template #default="scope">
         {{ scope.row.gender==1 ? '男' : '女'}}
        </template>
    </el-table-column>
    <el-table-column prop="phone" label="手机号" width="120" align="center"/>
    <el-table-column  label="最高学历" width="100" align="center">
      <template #default="scope">
          <span v-if="scope.row.degree == 1">初中</span>
          <span v-else-if="scope.row.degree == 2">高中</span>
          <span v-else-if="scope.row.degree == 3">专科</span>
          <span v-else-if="scope.row.degree == 4">本科</span>
          <span v-else-if="scope.row.degree == 5">硕士</span>
          <span v-else-if="scope.row.degree == 6">博士</span>
          <span v-else>其他</span>
        </template>
    </el-table-column>
    <el-table-column prop="violationCount" label="违纪次数" width="60" align="center"/>
    <el-table-column prop="violationScore" label="违纪扣分" width="60" align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center"/>
    <el-table-column prop="address" label="操作" align="center">
      <template #default="scope">
          <el-button size="small" @click="Edit(scope.row.id)">修改</el-button>
          <el-button size="small" type="warning" @click="openViolationDialog(scope.row.id)">违纪</el-button>
          <el-button size="small" type="danger" @click="deleteById(scope.row.id)">删除</el-button>
        </template>
    </el-table-column>
  </el-table>
  </div><br>

    <!-- 分页条 -->
    <div class="container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10, 20, 30, 50]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>

  <!-- 新增/修改员工的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="stuFrom" label-width="80px"  :rules="rules" ref="stuFormRef">
        <!-- 基本信息 -->
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="stuFrom.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-col>
           
          <el-col :span="12">
            <el-form-item label="学号" prop="no">
              <el-input v-model="stuFrom.no" placeholder="请输入学号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="stuFrom.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="gender in genders" :key="gender.name" :label="gender.name" :value="gender.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
 
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="stuFrom.phone" placeholder="请输入员工手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="stuFrom.idCard" placeholder="请输入身份证号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否院校" prop="isCollege">
              <el-select v-model="stuFrom.isCollege" placeholder="请选择性别" style="width: 100%;">
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系地址">
              <el-input v-model="stuFrom.address" placeholder="请输入联系地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最高学历">
              <el-select
                v-model="stuFrom.degree"
                placeholder="请选择"
                clearable>
                <el-option v-for="degrees in degreeList" :key="degrees.name" :label="degrees.name" :value="degrees.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
 
        <!-- 第五行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业时间">
              <el-date-picker
                v-model="stuFrom.graduationDate"
                type="date"
                placeholder="请选择毕业时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属班级">
              <el-select
                v-model="stuFrom.clazzId"
                placeholder="请选择"
                clearable>
                <el-option v-for="clazzs in clazzList" :key="clazzs.id" :label="clazzs.name"  :value="clazzs.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        </el-form>
       
      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

  <!-- 违纪对话款 -->
  <el-dialog v-model="dialogviolationFormVisible" title="提示" width="500">
    <el-form :model="violationFrom">
      <el-form-item label="请输入违纪扣分" :label-width="formLabelWidth">
        <el-input v-model="violationFrom.score" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogviolationFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveViolation">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>